package org.common.utils.generatortable.event;

import org.common.utils.database.access.DataAccess;
import org.common.utils.database.access.DataAccessTool;
import org.common.utils.database.access.DataSourceTool;
import org.common.utils.event.annotation.EventMethod;
import org.common.utils.field.FieldInfo;
import org.common.utils.field.GeneratorConfig;
import org.common.utils.generatortable.GeneratorTableManager;
import org.common.utils.generatortable.data.DataManager;
import org.common.utils.generatortable.data.entity.DataEntity;
import org.common.utils.generatortable.event.entity.GeneratorEvent;
import org.common.utils.generatortable.event.entity.MysqlConnectionEvent;
import org.common.utils.generatortable.event.entity.SelectDirEvent;
import org.common.utils.generatortable.event.entity.WindowCloseEvent;
import org.common.utils.generatortable.event.generator.GeneratorService;
import org.common.utils.generatortable.window.GeneratorTableWindow;
import org.common.utils.generatortable.window.tools.DialogTool;
import org.common.utils.tool.StringTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @author zhouzhibing
 * @date 2025/2/25
 */
public class CommonEventHandler {

    private Logger log = LoggerFactory.getLogger(CommonEventHandler.class);
    /**
     * 生成
     * @param event
     */
    @EventMethod
    public void generator(GeneratorEvent event) {
        String tableName = event.getTableName();
        if(StringTool.isEmpty(tableName)) {
            DialogTool.showMessageDialog("GeneratorTableWindow.dialog.generator.tableName.empty");
            return;
        }

        GeneratorTableManager manager = GeneratorTableManager.getInstance();
        JTextField txtGeneratorDir = manager.getComponent(JTextField.class, "txtGeneratorDir");
        JTextField txtPackageName = manager.getComponent(JTextField.class, "txtPackageName");

        String writePath = txtGeneratorDir.getText();
        String packageName = txtPackageName.getText();

//        writePath = "D:\\Workspaces\\idea-workspace\\common-utils\\utils\\src\\main\\java";
//        packageName = "org.common.utils.tableconfig.entity";

        DataAccess dataAccess = DataAccessTool.get().getDataAccess();
        List<FieldInfo> fieldList = dataAccess.select("show full columns from " + tableName, (result) -> {
            String columnName = result.getString(1);
            String columnType = result.getString(2);
            String columnComment = result.getString(9);
            return new FieldInfo(columnName , columnType , columnComment);
        });

        //是否kv配置的方式
        boolean isKvConfig = isKvConfig(fieldList);
        if (isKvConfig) {
            fieldList = dataAccess.select("select * from " + tableName, (result) -> {
                String columnName = result.getString(1);
                String columnType = result.getString(3);
                columnType = columnType == null ? "String" : columnType;
                String columnComment = result.getString(4);
                return new FieldInfo(columnName , columnType , columnComment);
            });
        }

        GeneratorConfig config = GeneratorConfig.newBuilder()
                .setWritePath(writePath)
                .setPackageName(packageName)
                .setTableName(tableName)
                .setFieldList(fieldList)
                .setKvConfig(isKvConfig)
                .build();

        GeneratorService.getInstance().generator(config);

        String title = manager.getString("GeneratorTableWindow.dialog.title");
        String text = manager.getString("GeneratorTableWindow.dialog.generator.success");
        JOptionPane.showMessageDialog(manager.getWindow(), text , title, JOptionPane.INFORMATION_MESSAGE);
    }

    /**
     * mysql连接事件
     * @param event 事件对象
     */
    @EventMethod
    public void mysqlConnection(MysqlConnectionEvent event) {
        //数据库已经连接
        if (DataAccessTool.get().isInit()) {
            DialogTool.showMessageDialog("GeneratorTableWindow.dialog.mysql.already.connect");
            return;
        }

        String host = event.getHost();
        String username = event.getUsername();
        String password = event.getPassword();
        CompletableFuture.runAsync(() -> {
            DataAccessTool.get().init(host, username, password);
            DataAccess dataAccess = DataAccessTool.get().getDataAccess();
            List<String> tableList = dataAccess.select("show tables", (result) -> result.getString(1));

            DefaultListModel<String> defaultListModel = new DefaultListModel<>();
            tableList.forEach(defaultListModel::addElement);

            JList<String> tblList = GeneratorTableManager.getInstance().getComponent(JList.class, "list1");
            tblList.setModel(defaultListModel);
        });
    }

    /**
     * 选择目标
     * @param event
     */
    @EventMethod
    public void selectDir(SelectDirEvent event) {
        JTextField txtGeneratorPath = event.getTxtGeneratorPath();
        JFrame mainFrame = event.getGeneratorTableWindow();

        JFileChooser jFileChooser = new JFileChooser();
        jFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int result = jFileChooser.showOpenDialog(mainFrame);
        if(result == JFileChooser.APPROVE_OPTION) {
            File selectedFile = jFileChooser.getSelectedFile();

            DataEntity dataEntity = GeneratorTableManager.getInstance().getDataManager().getDataEntity();
            dataEntity.setJavaDir(selectedFile.getAbsolutePath());

            txtGeneratorPath.setForeground(Color.BLACK);
            txtGeneratorPath.setText(selectedFile.getAbsolutePath());
            log.info("CommonEventHandler selectedFile = {} " , selectedFile.getAbsolutePath());
        }
    }

    /**
     * 窗口关闭
     * @param event 事件对象
     */
    @EventMethod
    public void windowClose(WindowCloseEvent event) {
        DataManager dataManager = GeneratorTableManager.getInstance().getDataManager();
        dataManager.save();
    }

    /**
     * 是否是kv配置，这里为4列
     * 第1列为key，第2列为value，第3列为type，第4列为desc
     * @param fieldList 字段列表
     * @return 是否是kv配置
     */
    private boolean isKvConfig(List<FieldInfo> fieldList) {
        if (fieldList.size() < 4) {
            return false;
        }

        FieldInfo keyField = fieldList.get(0);
        FieldInfo valueField = fieldList.get(1);
        FieldInfo typeField = fieldList.get(2);
        FieldInfo commentField = fieldList.get(3);

        return keyField.getColumnName().equals("key") &&
                valueField.getColumnName().equals("value") &&
                typeField.getColumnName().equals("type") &&
                commentField.getColumnName().equals("desc");
    }


}
